package utils.text;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 替换文本中的字符串，只能精确到一行
 * 
 * @author:张三石
 * @since:2021年9月14日 上午9:16:42
 */
public class ReplaceStrOnLine {
	// 计数
	public static int count = 0;
	public static String separator = System.getProperty("line.separator");//平台换行!

	public static void main(String[] args) {

		ReplaceStrOnLine replaceBatch = new ReplaceStrOnLine();

		File file = new File("C:\\Users\\o.o\\Desktop\\core");
		replaceBatch.loop(file);
		System.out.println(count);
	}

	void loop(File file) {
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			for (File obj : files) {
				loop(obj);
			}
		} else {
			setText(file, "目标字符串", "替换的字符串");
		}
	}

	public static void setText(File file, String target, String replacement) {//修改

		StringBuffer buffer = new StringBuffer();//临时容器!

		try (BufferedReader reader = new BufferedReader(new FileReader(file));) {

			for (String str = reader.readLine(); str != null; str = reader.readLine()) {
				if (str.contains(target)) {
					count++;
					str = str.replace(target, replacement);
				}
				buffer.append(str + separator);
			}

			try (PrintWriter writer = new PrintWriter(new FileWriter(file), true);) {
				writer.println(buffer);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}